//
//  KINGRefreshControl.swift
//  肉荣微博
//
//  Created by king on 15/8/4.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

let kRefreshPullOffset:CGFloat = -60.0

class KINGRefreshControl: UIRefreshControl {
    
    override init() {
        super.init()
        tintColor = UIColor.clearColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //print(frame)
        if frame.origin.y > 0 {
            return
        }
        if frame.origin.y > kRefreshPullOffset && !refreshView.retateFlag{
            print("赚回来")
            refreshView.retateFlag = true
        }
        if frame.origin.y < kRefreshPullOffset && refreshView.retateFlag{
            print("转过去")
            refreshView.retateFlag = false
        }
    }
    
    deinit {
        //移除观察者
        removeObserver(self, forKeyPath: "frame")
    }
    
    private func setupUI() {
        addSubview(refreshView)
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        //KVO添加观察者
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    //重写开始加载和停止加载函数
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startLoading()
    }
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    //懒加载控件
    private var refreshView:KINGRefreshView = {
        let refresh = KINGRefreshView.refreshView()
        return refresh
    }()
}

class KINGRefreshView: UIView {
    //定义旋转flag
    private var retateFlag = true {
        didSet {
            if retateFlag {
                tipLabel.text = "下拉刷新"
            } else {
                tipLabel.text = "上推取消"
            }
            pullImageAnimation()
        }
    }
    
    @IBOutlet weak var pullImage: UIImageView!
    @IBOutlet weak var tipView: KINGRefreshView!
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipLabel: UILabel!
    
    class func refreshView() -> KINGRefreshView {
        return NSBundle.mainBundle().loadNibNamed("KINGRefreshView", owner: nil, options: nil).last as! KINGRefreshView
    }
    
    func pullImageAnimation() {
        let angle:CGFloat = retateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        UIView.animateWithDuration(0.5) { () -> Void in
            self.pullImage.transform = CGAffineTransformRotate(self.pullImage.transform, angle)
        }
    }
    
    //开启加载动画
    private func startLoading() {
        //当每次改变的时候，都会创建一个动画，这时解决这个问题的方案有两种，一种是在设置一个开关，还有一个
        //方法就是在设置动画的时候指定一个key，然后根据在根据这个key做检索，如果存在就什么都不错
        //其实这里不用判断，因为如果key重复是不能添加动画的
        if loadingIcon.layer.animationForKey("startLoadingData") != nil {
            return
        }
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.repeatCount = MAXFLOAT
        anim.toValue = 2 * M_PI
        anim.duration = 10.0
        loadingIcon.layer.addAnimation(anim, forKey: "startLoadingData")
    }
    //停止加载动画
    private func stopLoading() {
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
}
